<script lang='ts' setup>
import { Message } from '@arco-design/web-vue';
import { ref } from 'vue';
import { AssetInfo } from '@/models/asset';
import { hope } from '@/tools/hope/@types/hope';
import { accept } from '@/models/chat-file';

const emits = defineEmits(['change'])
defineExpose({ getFiles })
const isLoading = ref(false);
const files = ref([] as AssetInfo[]);

function onBeforeUpload(file): boolean {

  console.log(file);
  isLoading.value = true;
  hope.upload({
    files: [file],
    success: (res) => {
      console.log(res);
      files.value = res
      isLoading.value = false;
    },
    complete: () => {
      isLoading.value = false;
    }
  })
  return true
}
const onSuccess = (res) => {
  console.log(res);
  const { response, file } = res;
  console.log(file);

  // files.value = [URL.createObjectURL(file)]
  isLoading.value = false;
};
const onError = () => {
  Message.error("失败了再试一次吧")
  isLoading.value = false;
};
function getFiles(): AssetInfo[] {
  setTimeout(() => {
    files.value = [];
  }, 100);
  return files.value;
}

</script>
<template>
  <div>
    <a-upload :auto-upload="false" :accept="'image/*,' + accept" :show-file-list="false" @success="onSuccess"
      @error="onError" @before-upload="onBeforeUpload">
      <template #upload-button>
        <a-spin v-if="isLoading" :size="25" />
        <div class="flex" v-else>
          <div class="image flex" @click.stop="null">
            <template v-for="file in files" :key="file.id">
              <a-image width="20" height="20" :src="file.url" fit="cover" v-if="file.format?.includes('image')" />
              <span v-else> {{ file.name }} </span>
            </template>
          </div>
          <slot></slot>
        </div>
      </template>
    </a-upload>
  </div>
</template>
<style lang='scss' scoped>
.image {
  margin: 0 4px;
}
</style>